<!-- Created by jack on 2022/3/17 - 17:17 -->
<style scoped lang="less">
.context-menu{
  user-select: none;
  background: #fff;
  padding: 4px;
  position: absolute;
  top: v-bind(top);
  left: v-bind(left);
  border-radius: 8px;
  box-shadow: 5px 5px 20px 1px rgba(0, 0, 0, 0.56);
  font-size: 14px;
  color: #838080;
  z-index: 200000;
  &__list{
    display: flex;
    flex-direction: column;
    &__item{
      border-radius: 8px;
      padding: 0 8px;
      height: 28px;
      display: flex;
      flex-direction: row;
      line-height: 28px;
      &:hover{
        cursor: pointer;
        background: rgba(142, 171, 208, 0.13);
      }
    }
  }
}


.fade-enter-active, .fade-leave-active{
  transition: all ease-in-out 200ms;
}
.fade-enter, .fade-leave-to{
  opacity: 0;
  transform: translateY(-10px);
}
</style>

<template>
  <transition name="fade" >
    <div class="context-menu" v-if="show" ref="contextMenu">
      <slot name="default">
        <div class="context-menu__list">
          <div class="context-menu__list__item" @click="clickItem(ele)" v-for="(ele,index) of props.fnList" :key="index">
            <img :src="ele.icon" class="context-menu__list__item__icon" v-if="ele.icon">
            <div class="context-menu__list__item__text">{{ ele.name }}</div>
          </div>
        </div>
      </slot>
    </div>
  </transition>
</template>

<script lang="ts" setup>
import {computed, onMounted, ref} from "vue";
import {getPointerPosition} from "@/helper";

const props = defineProps({
  id: null, // dom元素id
  fnList:{ type:Array,default: () => ([]) }, // 功能列表
})


/** 坐标动态值 */
let position:any = ref({})
const left = computed(_ => position && position.value?.x + 'px')
const top = computed(_ => position && position.value?.y + 'px')
/** 显示隐藏项 */
let show = ref(false)
/** 此dom */
let contextMenu = ref()

/** 点击菜单 */
const clickItem = (event:any) => {
  const { icon,name,cb } = event
  if(cb)cb()
  show.value = false
}

/** 添加鼠标右键🖱️事件 */
onMounted(() => {
  if(props.id){
    const dom = document.getElementById(props.id)
    document?.addEventListener('click',(event:MouseEvent) => {
      const { path,target } = event
      if(!path?.includes(contextMenu.value)){ // 右键点击不是body
        show.value = false
      }
    })
    dom?.addEventListener('contextmenu',(event:MouseEvent) => {
      position.value = getPointerPosition(event)
      show.value = true
    })

  }

})
</script>
